﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Management;
using System.Threading.Tasks;
using System.Windows.Forms;
using HuanQiuCrm.Properties;
using CCWin;
using WChat;

namespace HuanQiuCrm
{
    public partial class register : Skin_DevExpress
    {
        Settings st = new Settings();
        SqlHandle sql = new SqlHandle();

        //登录时用的数据库参数
        int _account_level, _allow_create, _allow_log, _use_message, _view_service, _view_sector, _export_news, _customer_analysis, _use_assistant, _check_all_message, _delete_customer_record, _manager_type;
        string _belong_account, _belong_depart, _user_name, _contact;

        public register()
        {
            InitializeComponent();
            //  UpdateVerifyCode();
        }
        int num = 1;

        //没有验证码的验证
        private void first_val()
        {
            string reg = tbx_name.Text;
            string pawd = tbx_pwd.Text;

            #region 没有用处
            //string res = sql.selectData(reg)[0];
            //string res = sql.;
            //sql.CreAllChiAccTab("HuanQiuYun");
            //if (pawd == res.Trim())
            //{

            //        //获取该账号的权限数据
            //        Get_Authority(reg);
            //        //保存配置文件
            //        Settings st = new Settings();
            //        st.UseAcct = reg;
            //        st.CanMass = _allow_create;
            //        st.CanMass = _allow_log;
            //        st.CanAddWx = _use_message;
            //        st.CanLooChaLog = _view_service;
            //        st.CanQuickReply = _view_sector;
            //        st.Save();
            //        this.Hide();
            //        Form1 main = new Form1();
            //        main.Show();
            //        num = 1;

            //}
            //else
            //{
            //    MessageBox.Show("账户名或密码输入不正确，请重新输入！");
            //    num++;
            //}
            #endregion

            if (sql.Select_child_acct(reg))
            {
                if (pawd == sql.Select_child_Pass(reg)[0].Trim())
                {
                    string admin = sql.Select_child_Admin(reg)[0];
                    ChiAcc asd = new ChiAcc();
                    asd = sql.GetChiInfo(admin.Trim(),reg);
                    Settings st = new Settings();
                    st.Admin = admin.Trim();
                    st.UseAcct = reg;
                    st.UsePas = pawd;
                    st.CanChat = asd.CanChat;
                    st.CanViNots = asd.CanViNots;
                    st.CanMass = asd.CanMass;
                    st.CanRob = asd.CanRob;
                    st.CanAddWx = asd.CanAddWx;
                    st.CanLooChaLog = asd.CanLooChaLog;
                    st.CanQuickReply = asd.CanQuickReply;                    
                    st.Save();
                    this.Hide();
                    Form1 main = new Form1();
                    main.Show();
                    num = 1;
                }
                else
                {
                    MessageBox.Show("密码不正确，请重新输入！");
                }
            }
            else
            {
                MessageBox.Show("用户名不存在");
            } 

        }

        //有验证码的验证
        private void second_val()
        {
            string reg = tbx_name.Text;
            string pawd = tbx_pwd.Text;
            if (tbx_code.Text == strVerifyCode)
            {
                if (sql.Select_child_acct(reg))
                {
                    if (pawd == sql.Select_child_Pass(reg)[0].Trim())
                    {
                        string admin = sql.Select_child_Admin(reg)[0];
                        ChiAcc asd = new ChiAcc();
                        asd = sql.GetChiInfo(admin.Trim(), reg);

                        Settings st = new Settings();
                        st.Admin = admin.Trim();   //将管理员信息存入
                        st.UseAcct = reg;
                        st.UsePas = pawd;
                        st.CanChat = asd.CanChat;
                        st.CanViNots = asd.CanViNots;
                        st.CanMass = asd.CanMass;
                        
                        st.CanRob = asd.CanRob;
                        st.CanAddWx = asd.CanAddWx;
                        st.CanLooChaLog = asd.CanLooChaLog;
                        st.CanQuickReply = asd.CanQuickReply;
                        st.Save();
                        this.Hide();
                        Form1 main = new Form1();
                        main.Show();
                        num = 1;
                    }
                    else
                    {
                        MessageBox.Show("密码不正确，请重新输入！");
                    }
                }
                else
                {
                    MessageBox.Show("用户名不存在");
                }
            }
            else
            {
                MessageBox.Show("验证码输入不正确，请重新输入！");
                UpdateVerifyCode();
            }
        }

        //获取权限
        private void Get_Authority(string reg)
        {
            _account_level = int.Parse(sql.select_account_level(reg)[0]); //账户等级
            _belong_account = sql.select_belong_account(reg)[0];  //账户所属
            _allow_create = int.Parse(sql.select_allow_create(reg)[0]);  //是否允许创建子账户
            _allow_log = int.Parse(sql.select_allow_log(reg)[0]);  //是否允许登录客户端
            _use_message = int.Parse(sql.select_use_message(reg)[0]);  //是否允许使用消息管理
            _view_service = int.Parse(sql.select_view_service(reg)[0]);   //是否允许查看其他客服消息记录
            _view_sector = int.Parse(sql.select_view_sector(reg)[0]);  //是否允许查看其他部门消息记录
        }

        //密码提醒
        private void tbx_pwd_MouseEnter(object sender, EventArgs e)
        {
            ToolTip p = new ToolTip();
            p.ShowAlways = true;
            p.SetToolTip(this.tbx_pwd, "请注意：密码为注册码");
        }

        #region 根据机器码获得注册码
        // 取得设备硬盘的卷标号
        public static string GetDiskVolumeSerialNumber()
        {
            ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
            ManagementObject disk = new ManagementObject("win32_logicaldisk.deviceid=\"d:\"");
            disk.Get();
            return disk.GetPropertyValue("VolumeSerialNumber").ToString();
        }

        //获得CPU的序列号
        public static string getCpu()
        {
            string strCpu = null;
            ManagementClass myCpu = new ManagementClass("win32_Processor");
            ManagementObjectCollection myCpuConnection = myCpu.GetInstances();
            foreach (ManagementObject myObject in myCpuConnection)
            {
                strCpu = myObject.Properties["Processorid"].Value.ToString();
                break;
            }
            return strCpu;
        }
        //生成机器码
        public static string getMNum()
        {
            string strNum = getCpu() + GetDiskVolumeSerialNumber();//获得24位Cpu和硬盘序列号
            string strMNum = strNum.Substring(0, 24);//从生成的字符串中取出前24个字符做为机器码
            return strMNum;
        }
        public static int[] intCode = new int[127];//存储密钥
        public static int[] intNumber = new int[25];//存机器码的Ascii值
        public static char[] Charcode = new char[25];//存储机器码字
        public static void setIntCode()//给数组赋值小于10的数
        {
            for (int i = 1; i < intCode.Length; i++)
            {
                intCode[i] = i % 9;
            }
        }


        //生成注册码     
        public static string getRNum()
        {
            setIntCode();//初始化127位数组
            for (int i = 1; i < Charcode.Length; i++)//把机器码存入数组中
            {
                Charcode[i] = Convert.ToChar(getMNum().Substring(i - 1, 1));
            }
            for (int j = 1; j < intNumber.Length; j++)//把字符的ASCII值存入一个整数组中。
            {
                intNumber[j] = intCode[Convert.ToInt32(Charcode[j])] + Convert.ToInt32(Charcode[j]);
            }
            string strAsciiName = "";//用于存储注册码
            for (int j = 1; j < intNumber.Length; j++)
            {
                if (intNumber[j] >= 48 && intNumber[j] <= 57)//判断字符ASCII值是否0－9之间
                {
                    strAsciiName += Convert.ToChar(intNumber[j]).ToString();
                }
                else if (intNumber[j] >= 65 && intNumber[j] <= 90)//判断字符ASCII值是否A－Z之间
                {
                    strAsciiName += Convert.ToChar(intNumber[j]).ToString();
                }
                else if (intNumber[j] >= 97 && intNumber[j] <= 122)//判断字符ASCII值是否a－z之间
                {
                    strAsciiName += Convert.ToChar(intNumber[j]).ToString();
                }
                else//判断字符ASCII值不在以上范围内
                {
                    if (intNumber[j] > 122)//判断字符ASCII值是否大于z
                    {
                        strAsciiName += Convert.ToChar(intNumber[j] - 10).ToString();
                    }
                    else
                    {
                        strAsciiName += Convert.ToChar(intNumber[j] - 9).ToString();
                    }
                }
            }
            return strAsciiName;
        }


        #endregion

        #region 注册按钮 注册事件
        private void btn_registerr_Click(object sender, EventArgs e)
        {

            register_account asd = new register_account();
            asd.Show();
        }
        private Boolean CheckRegist(string code)
        {
            bool su = false;
            //this.btn_reg.Enabled = true;

            // RegistryKey retkey = Microsoft.Win32.Registry.CurrentUser.OpenSubKey("software", true).CreateSubKey("wxk").CreateSubKey("wxk.INI");
            //foreach (string strRNum in retkey.GetSubKeyNames())//判断是否注册
            //{
            if (code == getRNum())
            {
                MessageBox.Show("恭喜您注册成功！");
                su = true;
            }
            //}
            else
            {
                MessageBox.Show("很遗憾您注册失败！");
            }
            return su;
        }
        #endregion

        #region 验证码生成


        //随机码
        private String strVerifyCode = "";

        //更新验证码
        private void UpdateVerifyCode()
        {
            strVerifyCode = CreateRandomCode();
            CreateImage(strVerifyCode);
        }
        private string CreateRandomCode()
        {
            int rand;
            char code;
            string randomCode = String.Empty;
            //生成一定长度的验证码
            System.Random random = new Random();
            for (int i = 0; i < 5; i++)
            {
                rand = random.Next();
                if (rand % 3 == 0)
                {
                    code = (char)('A' + (char)(rand % 26));
                }
                else
                {
                    code = (char)('0' + (char)(rand % 10));
                }
                randomCode += code.ToString();
            }
            // MessageBox.Show("这"+randomCode);
            return randomCode;
        }
        ///  创建随机码图片
        private void CreateImage(string strVerifyCode)
        {
            try
            {
                int iRandAngle = 45;    //随机转动角度
                int iMapWidth = (int)(strVerifyCode.Length * 21);
                Bitmap map = new Bitmap(iMapWidth, 28);     //创建图片背景

                Graphics graph = Graphics.FromImage(map);
                graph.Clear(Color.AliceBlue);//清除画面，填充背景
                graph.DrawRectangle(new Pen(Color.Black, 0), 0, 0, map.Width - 1, map.Height - 1);//画一个边框
                graph.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;//模式
                Random rand = new Random();
                //背景噪点生成
                Pen blackPen = new Pen(Color.LightGray, 0);
                for (int i = 0; i < 50; i++)
                {
                    int x = rand.Next(0, map.Width);
                    int y = rand.Next(0, map.Height);
                    graph.DrawRectangle(blackPen, x, y, 1, 1);
                }
                //验证码旋转，防止机器识别
                char[] chars = strVerifyCode.ToCharArray();//拆散字符串成单字符数组
                //文字距中
                StringFormat format = new StringFormat(StringFormatFlags.NoClip);
                format.Alignment = StringAlignment.Center;
                format.LineAlignment = StringAlignment.Center;
                //定义颜色
                Color[] c = { Color.Black, Color.Red, Color.DarkBlue, Color.Green, Color.Orange, Color.Brown, Color.DarkCyan, Color.Purple };
                //定义字体
                string[] font = { "Verdana", "Microsoft Sans Serif", "Comic Sans MS", "Arial", "宋体" };
                for (int i = 0; i < chars.Length; i++)
                {
                    int cindex = rand.Next(7);
                    int findex = rand.Next(5);
                    Font f = new System.Drawing.Font(font[findex], 13, System.Drawing.FontStyle.Bold);//字体样式(参数2为字体大小)
                    Brush b = new System.Drawing.SolidBrush(c[cindex]);
                    Point dot = new Point(16, 16);

                    float angle = rand.Next(-iRandAngle, iRandAngle);//转动的度数
                    graph.TranslateTransform(dot.X, dot.Y);//移动光标到指定位置
                    graph.RotateTransform(angle);
                    graph.DrawString(chars[i].ToString(), f, b, 1, 1, format);

                    graph.RotateTransform(-angle);//转回去
                    graph.TranslateTransform(2, -dot.Y);//移动光标到指定位置
                }
                pictureBox1.Image = map;

            }
            catch (ArgumentException)
            {
                MessageBox.Show("创建图片错误。");
            }
        }

        //private void pictureBox1_Click(object sender, EventArgs e) {

        //}

        //private void pictureBox1_MouseEnter(object sender, EventArgs e) {
        //    ToolTip p = new ToolTip();
        //    p.ShowAlways = true;
        //    p.SetToolTip(this.pictureBox1, "看不清,点击换一张");
        //}


        #endregion
        //登录按钮事件
        private void btn_login_Click(object sender, EventArgs e)
        {
            if (num < 3)
            {
                first_val();
            }
            else
            {
                skinLabel1.Visible = true;
                pictureBox1.Visible = true;
                tbx_code.Visible = true;

                second_val();
            }
        }

        private void pictureBox1_Click_1(object sender, EventArgs e)
        {
            UpdateVerifyCode();
        }

        private void pictureBox1_MouseEnter(object sender, EventArgs e)
        {
            ToolTip p = new ToolTip();
            p.ShowAlways = true;
            p.SetToolTip(this.pictureBox1, "看不清,点击换一张");
        }
    }
}
